<!-- 组织机构列表-新增组织 -->
<template>
  <a-modal
    width="50%"
    :visible="props.visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    draggable
    title-align="center"
    unmount-on-close
  >
    <template #title> 新增组织 </template>
    <div style="padding: 10px 20px">
      <a-form :model="formData" ref="refForm" auto-label-width>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              label="上级组织"
              show-colon
              label-col-flex="150px"
              :field="`superiorId`"
              :rules="[
                {
                  required: isHaveHeadoffice ? true : false,
                  message: '请选择上级组织'
                },
                {
                  validator: superiorValidate
                }
              ]"
            >
              <a-tree-select
                v-model="formData.superiorId"
                :data="organizationType"
                :placeholder="
                  isHaveHeadoffice ? '请选择上级组织' : '新增一个总公司'
                "
                style="width: 300px"
                :field-names="{
                  key: 'id',
                  title: 'C30BBF36A5AF541F7A2657671DEE2EDD6'
                }"
                :disabled="!isHaveHeadoffice || !!superiorId"
                allow-search
                @change="handleSuperior"
                dropdown-class-name="tree-drop-down-indent-size"
              >
                <template #tree-slot-switcher-icon="node, { isLeaf }">
                  <IconDown v-if="!isLeaf" />
                  <IconStar v-if="isLeaf" />
                </template>
                <template #tree-slot-title="nodeData">
                  <span
                    :style="{
                      paddingLeft:
                        nodeData.level > 2
                          ? '32px'
                          : (nodeData.level - 1) * 16 + 'px'
                    }"
                  >
                    {{ nodeData['C30BBF36A5AF541F7A2657671DEE2EDD6'] }}
                  </span>
                </template>
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="最大编制人数"
              :field="`superiorId`"
              show-colon
              label-col-flex="150px"
              :rules="[
                {
                  required: true
                }
              ]"
            >
              <a-input v-model="maxHeadCount" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :rules="[
                {
                  required: true
                }
              ]"
              label-col-flex="150px"
              label="最大可支配编制人数"
              :field="`superiorId`"
              show-colon
            >
              <a-input v-model="maxDisposableHeadCount" disabled></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-scrollbar style="height: 500px; overflow: auto">
          <a-row>
            <a-col :span="12">
              <a-form-item
                :field="`organizationLists[0].organizationValue.name`"
                :rules="[
                      {
                        required: true,
                        message: '请输入'
                      },
                      {
                        validator: (val:any, cb: any) => validate(val, cb, 1)
                      }
                    ]"
                label="组织名称"
                show-colon
              >
                <a-input
                  v-model="formData.organizationLists[0].organizationValue.name"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :field="`organizationLists[0].organizationValue.organizationUniqueCode`"
                label="组织编码"
                show-colon
              >
                <a-input
                  v-model="
                    formData.organizationLists[0].organizationValue
                      .organizationUniqueCode
                  "
                ></a-input>
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item
                :field="`organizationLists[0].organizationValue.ownerId`"
                :rules="[
                  {
                    required: true,
                    message: '请输入'
                  }
                ]"
                label="组织类型"
                show-colon
              >
                <a-select
                  placeholder="请选择"
                  v-model="
                    formData.organizationLists[0].organizationValue.ownerId
                  "
                  @change="
                    (value, record1, rowIndex1) =>
                      selectType(value, formData.organizationLists[0], 0)
                  "
                  @clear="
                    (record1, rowIndex1) =>
                      clearType(formData.organizationLists[0], 0)
                  "
                  allow-search
                  allow-clear
                >
                  <a-option
                    v-for="item in typeList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  ></a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :field="`organizationLists[0].organizationValue.templateId`"
                :rules="[
                  {
                    required: true,
                    message: '请输入'
                  }
                ]"
                label="选择组织模板"
                show-colon
              >
                <a-select
                  placeholder="请选择"
                  v-model="
                    formData.organizationLists[0].organizationValue.templateId
                  "
                  allow-search
                  allow-clear
                >
                  <a-option
                    v-for="item in templateList[0]"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  ></a-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item
                :field="`organizationLists[0].organizationValue.headcount`"
                label="编制人数"
                show-colon
              >
                <a-input-number
                  v-model="
                    formData.organizationLists[0].organizationValue.headcount
                  "
                  :min="1"
                  :precision="0"
                  hide-button
                ></a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :field="`organizationLists[0].organizationValue.responsibleId`"
                label="组织负责人"
                show-colon
              >
                <a-select
                  placeholder="请选择"
                  v-model="
                    formData.organizationLists[0].organizationValue
                      .responsibleId
                  "
                  allow-search
                  allow-clear
                  @popup-visible-change="showHumanModal(1, 0)"
                >
                  <a-option
                    :label="
                      formData.organizationLists[0].organizationValue
                        .responserName
                    "
                    :value="
                      formData.organizationLists[0].organizationValue
                        .responsibleId
                    "
                  ></a-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item
                :field="`organizationLists[0].organizationValue.leaderId`"
                label="分管领导"
                show-colon
              >
                <a-select
                  placeholder="请选择"
                  v-model="
                    formData.organizationLists[0].organizationValue.leaderId
                  "
                  allow-search
                  allow-clear
                  @popup-visible-change="showHumanModal(2, 0)"
                  multiple
                >
                  <a-option
                    v-for="item in formData.organizationLists[0]
                      .organizationValue.leaderName"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  ></a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :field="`organizationLists[0].organizationValue.workPlace`"
                label="工作地点"
                show-colon
              >
                <a-select
                  ref="workPlaceRef"
                  placeholder="请选择"
                  v-model="
                    formData.organizationLists[0].organizationValue.workPlace
                  "
                  allow-search
                  allow-clear
                >
                  <a-option
                    v-for="item in addressList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  ></a-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item
                :field="`organizationLists[0].organizationValue.islegalPerson`"
                label="是否为独立法人"
                show-colon
              >
                <a-radio-group
                  v-model="
                    formData.organizationLists[0].organizationValue
                      .islegalPerson
                  "
                >
                  <a-radio
                    :disabled="
                      formData.organizationLists[0].organizationValue.node ===
                      '部门'
                    "
                    value="是"
                    >是</a-radio
                  >
                  <a-radio value="否">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :field="`organizationLists[0].organizationValue.isVirtualOrganization`"
                label="是否为虚拟组织"
                show-colon
              >
                <a-radio-group
                  v-model="
                    formData.organizationLists[0].organizationValue
                      .isVirtualOrganization
                  "
                >
                  <a-radio value="是">是</a-radio>
                  <a-radio value="否">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item
                :field="`organizationLists[0].organizationValue.enable`"
                label="是否启用该组织"
                show-colon
              >
                <a-radio-group
                  v-model="
                    formData.organizationLists[0].organizationValue.enable
                  "
                >
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="2">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
        </a-scrollbar>

        <!-- <a-form-item hide-label>
          <a-table
            :data="formData.organizationLists"
            :pagination="false"
            stripe
          >
            <template #columns>
              <a-table-column
                :width="100"
                title="操作"
                v-if="organizationType?.length > 0"
              >
                <template #cell="{ rowIndex }">
                  <div class="operation">
                    <icon-plus-circle-fill
                      class="icon"
                      :style="{
                        color: '#165dff',
                        marginRight: '10px'
                      }"
                      @click="add(rowIndex)"
                    />
                    <icon-delete
                      class="icon"
                      :style="{
                        color: 'red'
                      }"
                      @click="del(rowIndex)"
                      v-if="formData.organizationLists.length > 1"
                    />
                  </div>
                </template>
              </a-table-column>
              <a-table-column :width="200" title="组织名称" data-index="name">
                <template #title>
                  <span class="star">组织名称</span>
                </template>
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`organizationLists.${rowIndex}.organizationValue.name`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入'
                      },
                      {
                        validator: (val:any, cb: any) => validate(val, cb, 1)
                      }
                    ]"
                    hide-label
                  >
                    <a-input v-model="record.organizationValue.name"></a-input>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column
                :width="200"
                title="组织编码"
                data-index="organizationUniqueCode"
              >
                <template #title>
                  <span>组织编码</span>
                </template>
                <template #cell="{ record }">
                  <a-form-item hide-label>
                    <a-input
                      v-model="record.organizationValue.organizationUniqueCode"
                    ></a-input>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column
                :width="200"
                title="组织类型"
                data-index="ownerId"
              >
                <template #title>
                  <span class="star">组织类型</span>
                </template>
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`organizationLists.${rowIndex}.organizationValue.ownerId`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入'
                      }
                    ]"
                    hide-label
                  >
                    <a-select
                      placeholder="请选择"
                      v-model="record.organizationValue.ownerId"
                      @change="
                        (value, record1, rowIndex1) =>
                          selectType(value, record, rowIndex)
                      "
                      @clear="
                        (record1, rowIndex1) => clearType(record, rowIndex)
                      "
                      allow-search
                      allow-clear
                    >
                      <a-option
                        v-for="item in typeList"
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                      ></a-option>
                    </a-select>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column
                :width="150"
                title="选择组织模板"
                data-index="headcount"
              >
                <template #title>
                  <span class="star"
                    >选择组织模板
                    <a-tooltip
                      content="注意：如果先选择了组织类型，则优先使用对应组织类型里面的模板。否则优先使用组织模板库的模板！"
                    >
                      <icon-exclamation-circle-fill style="color: #165dff" />
                    </a-tooltip>
                  </span>
                </template>
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`organizationLists.${rowIndex}.organizationValue.templateId`"
                    :rules="[
                      {
                        required: true,
                        message: '请选择'
                      }
                    ]"
                    hide-label
                  >
                    <a-select
                      placeholder="请选择"
                      v-model="record.organizationValue.templateId"
                      allow-search
                      allow-clear
                    >
                      <a-option
                        v-for="item in templateList[rowIndex]"
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                      ></a-option>
                    </a-select>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column
                :width="120"
                title="编制人数"
                data-index="headcount"
              >
                <template #title>
                  <span>编制人数</span>
                </template>
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`organizationLists.${rowIndex}.organizationValue.headcount`"
                    hide-label
                  >
                    <a-input-number
                      v-model="record.organizationValue.headcount"
                      :min="1"
                      :precision="0"
                      hide-button
                    ></a-input-number>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column
                :width="150"
                title="组织负责人 "
                data-index="responsibleId"
              >
                <template #title>
                  <span>组织负责人</span>
                </template>
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`organizationLists.${rowIndex}.organizationValue.responsibleId`"
                    hide-label
                  >
                    <a-select
                      placeholder="请选择"
                      v-model="record.organizationValue.responsibleId"
                      allow-search
                      allow-clear
                      @popup-visible-change="showHumanModal(1, rowIndex)"
                    >
                      <a-option
                        :label="record.organizationValue.responserName"
                        :value="record.organizationValue.responsibleId"
                      ></a-option>
                    </a-select>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column
                :width="150"
                title="分管领导"
                data-index="leaderId"
              >
                <template #cell="{ record, rowIndex }">
                  <a-form-item hide-label>
                    <a-select
                      placeholder="请选择"
                      v-model="record.organizationValue.leaderId"
                      allow-search
                      allow-clear
                      @popup-visible-change="showHumanModal(2, rowIndex)"
                      multiple
                    >
                      <a-option
                        v-for="item in record.organizationValue.leaderName"
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                      ></a-option>
                    </a-select>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column
                :width="150"
                title="工作地点"
                data-index="workPlace"
              >
                <template #title>
                  <span class="star">工作地点</span>
                </template>
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`organizationLists.${rowIndex}.organizationValue.workPlace`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入'
                      }
                    ]"
                    hide-label
                  >
                    <a-select
                      ref="workPlaceRef"
                      placeholder="请选择"
                      v-model="record.organizationValue.workPlace"
                      allow-search
                      allow-clear
                    >
                      <a-option
                        v-for="item in addressList"
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                      ></a-option>
                    </a-select>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column
                :width="160"
                title="是否为独立法人"
                data-index="islegalPerson"
              >
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`organizationLists.${rowIndex}.organizationValue.islegalPerson`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入'
                      }
                    ]"
                    hide-label
                  >
                    <a-radio-group
                      v-model="record.organizationValue.islegalPerson"
                    >
                      <a-radio
                        :disabled="record.organizationValue.node === '部门'"
                        value="是"
                        >是</a-radio
                      >
                      <a-radio value="否">否</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column
                :width="160"
                title="是否为虚拟组织"
                data-index="name"
              >
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`organizationLists.${rowIndex}.organizationValue.isVirtualOrganization`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入'
                      }
                    ]"
                    hide-label
                  >
                    <a-radio-group
                      v-model="record.organizationValue.isVirtualOrganization"
                    >
                      <a-radio value="是">是</a-radio>
                      <a-radio value="否">否</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column
                :width="160"
                title="是否启用该组织"
                data-index="name"
              >
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`organizationLists.${rowIndex}.organizationValue.enable`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入'
                      }
                    ]"
                    hide-label
                  >
                    <a-radio-group v-model="record.organizationValue.enable">
                      <a-radio :value="1">是</a-radio>
                      <a-radio :value="2">否</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-form-item> -->
      </a-form>
    </div>
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button
        type="primary"
        @click="handleOk(false)"
        :loading="store.isLoading"
        >确定</a-button
      >
      <a-button
        type="primary"
        @click="handleOk(true)"
        :loading="store.isLoading"
        >确定并继续新增</a-button
      >
    </template>
  </a-modal>
  <HumanRosterModal
    style="z-index: 9999"
    v-model:visible="humanModalVisible"
    @humanRosterEmit="humanRosterEmit"
    :rowSelectionType="rowSelection"
  ></HumanRosterModal>
</template>

<script lang="ts" setup>
import {
  OrganizationPatternSearch,
  GetDepartmentTemplate
} from '@/apis/management/organization/baseSetting/organizationalType';
import { GetUserList } from '@/apis/management/user';
import {
  GetWorkPlaceList,
  PostOrganizationList,
  GetOrganizationList,
  GetOrganizationDownNum,
  GetOrganizationHeaderSetting,
  GetCheckOrganization
} from '@/apis/management/organization/organizationManagement';
import { GetPositionDefault } from '@/apis/management/organization/positionManagement';
import { GetHeaderSetting } from '@/apis/management/base';
import { dataTreeFilter, flatTree } from '@/utils/utils';
import { cloneDeep } from 'lodash';
import { Message } from '@arco-design/web-vue';
import TabItem from '@/components/TabBar/TabItem.vue';
import { validateRules } from '@/utils/common';
import { CheckJobNumToOrganizaitonId } from '@/apis/management/personnel/baseSetting/TransactionSetting';
import useGlobalParametersStore from '@/store/modules/globalParameters';

const store = useGlobalParametersStore();
// import HumanRosterModal from '../HumanRosterModal/index.vue';

const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    superiorData: any; // 上级组织数据
    superiorId?: number | undefined;
  }>(),
  {
    visible: false,
    superiorId: undefined
  }
);

const emit = defineEmits(['update:visible', 'organizationAddEmit']);

let rowSelection = reactive({
  type: 'radio'
});

// 上级组织限制,只能存在一个最大的组织
const superiorValidate = (val: any, cb: any) => {
  // 如果存在最大的组织，则一定要选择一个上级组织
  if (isHaveHeadoffice.value && !val) cb('请选择一个组织！');
  else return;
};

let maxHeadCount = ref<number | string>(0), // 最大编制人数
  maxDisposableHeadCount = ref<number | string>(0); // 最大可支配编制人数
// 获取最大编制人数
const getMaxHeadCount = async () => {
  const { controlType, percentage, warning, headcount } = currSuperiorData;
  console.log(
    'controlType, percentage, warning, headcount ',
    controlType,
    percentage,
    warning,
    headcount,
    currSuperiorData
  );

  // 获取该上级组织下面的全部在职人数
  const downNum = await GetOrganizationDownNum({
    id: formData.superiorId
  });
  console.log('====================================');
  console.log(downNum);
  console.log('====================================');
  // 无编制
  if (controlType === 1) {
    maxHeadCount.value = '∞';
    maxDisposableHeadCount.value = '∞';
  }
  // 非严格控编
  else if (controlType === 2) {
    maxHeadCount.value = headcount + Math.floor(percentage * 0.01 * headcount);
    maxDisposableHeadCount.value = maxHeadCount.value - downNum;
  } else if (controlType === 3) {
    maxHeadCount.value = headcount;
  }
};
// 组织名称、组织编码查重
const validate = async (val: any, cb: any, type: number) => {
  try {
    if (!val) return;
    /*
      type 1为组织名称 2组织编码
    */
    let data = {
      superiorId: formData.superiorId ? formData.superiorId : 0,
      type,
      name: val
    };
    const res = await validateRules(GetCheckOrganization, data);
    if (res.code) {
      cb(`${res.msg}`);
    } else return;
  } catch (error: unknown) {
    console.log(error);
  }
};

const organizationType = ref<any>([]); // 储存上级组织
let flatOrganizationList: any = []; // 储存扁平化的组织数据
let currSuperiorData: any = {}; // 当前选择的上级组织的数据
const typeList = ref<any>([]); // 储存组织类型后台数据
const userList = ref<any>([]); // 储存人员数据
const addressList = ref<any>([]); // 储存工作地点后台数据
let templateList = ref<any>([]); // 储存模板数据
let workPlaceRef = ref(); // 储存工作地点下拉框的ref
let headerSetting = ref<any>([]);
let isHaveHeadoffice = ref(true); // 是否存在总公司
const getData = async () => {
  try {
    const userId = +(localStorage.getItem('userId') as string);
    const [
      organizationList,
      patternSearch,
      workplaceList,
      headerSetting,
      templateListRes
    ] = await Promise.all([
      GetOrganizationList({}),
      OrganizationPatternSearch({
        pageNumber: 0,
        pageSize: -1
      }),
      GetWorkPlaceList({
        pageNumber: 0,
        pageSize: -1
      }),
      GetHeaderSetting({
        ownerFuncType: 1,
        userId
      }),
      GetDepartmentTemplate({
        pageNumber: 0,
        pageSize: -1,
        ownerType: 3
      })
    ]);
    organizationType.value =
      organizationList.length > 0
        ? dataTreeFilter(organizationList, 'enable')
        : [];
    flatOrganizationList =
      organizationList.length > 0
        ? flatTree(dataTreeFilter(organizationList))
        : [];

    isHaveHeadoffice.value = organizationList.length > 0;
    typeList.value = patternSearch.content.filter((el: any) => el.status === 1);
    addressList.value = workplaceList.content;

    templateList.value[0] = templateListRes.content?.filter(
      (item: any) => item.enable === 1
    );
  } catch (error) {
    console.log(error);
  }
};

// 储存表单信息
const formData = reactive<any>({
  superiorId: undefined, // 上级组织Id
  organizationLists: [
    {
      superiorId: undefined, // 上级组织Id
      name: '', // 组织名称
      organizationUniqueCode: '', // 组织编码
      ownerId: undefined, // 组织类型Id,
      node: '', // 组织节点
      enable: 1, // 是否启用
      positionName: '', // 负责人职位名称
      headcount: undefined, // 编制人数
      responsibleId: undefined, // 组织负责人的userId
      responserName: '', // 组织负责人姓名
      leaderName: '', // 分管领导名称
      leaderId: undefined, // 分管领导id
      numId: 0, // 工号规则id
      // 储存表格信息
      organizationValue: {
        name: '', // 组织名称
        organizationUniqueCode: '', // 编码
        ownerId: undefined, // 组织类型id
        node: '', // 组织节点
        templateId: undefined, // 模板id
        headcount: undefined, // 编制人数
        responsibleId: undefined, // 组织负责人userId
        responserName: '', // 组织负责人姓名
        positionName: '', // 组织负责人职位
        leaderId: undefined, // 分管领导userId
        leaderName: '', // 分管领导姓名
        workPlace: undefined, // 工作地点
        islegalPerson: '否', // 是否为独立法人
        isVirtualOrganization: '是', // 是否为虚拟组织,
        superiorId: undefined, // 上级组织id
        enable: 1 // 是否启用该组织 1是2否
      },
      organizationalData: [{}]
    }
  ]
});

const tempItem = {
  superiorId: undefined, // 上级组织Id
  name: '', // 组织名称
  organizationUniqueCode: '', // 组织编码
  ownerId: undefined, // 组织类型Id,
  node: '', // 组织节点
  enable: 1, // 是否启用
  positionName: '', // 负责人职位名称
  responsibleId: undefined, // 组织负责人的userId
  headcount: undefined, // 编制人数
  responserName: '', // 组织负责人姓名
  leaderName: [], // 分管领导名称
  leaderId: [], // 分管领导id
  // 储存表格信息
  organizationValue: {
    name: '', // 组织名称
    organizationUniqueCode: '', // 编码
    ownerId: undefined, // 组织类型id
    node: '', // 组织节点
    templateId: undefined, // 模板id
    headcount: undefined, // 编制人数
    responsibleId: undefined, // 组织负责人userId
    responserName: '', // 组织负责人姓名
    positionName: '', // 组织负责人职位
    leaderId: [], // 分管领导userId
    leaderName: [], // 分管领导姓名
    workPlace: undefined, // 工作地点
    islegalPerson: '否', // 是否为独立法人
    isVirtualOrganization: '是', // 是否为虚拟组织,
    superiorId: undefined, // 上级组织id
    enable: 1 // 是否启用该组织 1是2否
  },
  organizationalData: [{}]
};

watch(
  () => props.visible,
  (newVal: boolean, oldVal: boolean) => {
    if (newVal) {
      getData(); // 如果弹出框显示才获取数据
      if (props.superiorId) {
        formData.superiorId = props.superiorId;
        currSuperiorData = cloneDeep(props.superiorData);
        getMaxHeadCount();
      }
    }
  }
);

// 上级组织下拉选择框
const handleSuperior = async (id: number) => {
  try {
    // 判断该组织是否的工号规则是否使用了全局统一，如果是则传该上级组织id，否则为0
    const { isDown } = await CheckJobNumToOrganizaitonId({
      id
    });
    if (isDown === 1) {
      formData.organizationLists[0].numId = id;
    } else formData.organizationLists[0].numId = 0;

    // 获取选择的上级组织数据并重新赋值最大编制人数
    currSuperiorData = flatOrganizationList.find((item: any) => item.id === id);
    getMaxHeadCount();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 组织类型下拉框，用来获取默认模板id
const selectType = async (value, record: any, index: number) => {
  try {
    if (!record.organizationValue.templateId) {
      const { content } = await GetDepartmentTemplate({
        pageNumber: 0,
        pageSize: -1,
        ownerType: 1,

        ownerId: record.organizationValue.ownerId
      });
      record.organizationValue.node = typeList.value.find(
        (el: any) => el.id === record.organizationValue.ownerId
      )?.node;
      record.organizationValue.templateId = undefined;
      templateList.value[index] = content?.filter(
        (item: any) => item.enable === 1
      );
      record.organizationValue.templateId = templateList.value[index].find(
        (item: any) => item.isShowDefault === 1
      )?.id;
      console.log('======================templateId==============');
      console.log(record.organizationValue.templateId);
      console.log(content);
      console.log('====================================');
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const clearType = async (record: any, index: number) => {
  try {
    nextTick(async () => {
      record.organizationValue.templateId = undefined;
      const { content } = await GetDepartmentTemplate({
        pageNumber: 0,
        pageSize: -1,
        ownerType: 3
      });
      templateList.value[index] = content?.filter(
        (item: any) => item.enable === 1
      );
      console.log('=========record===========================');
      console.log(templateList.value[index], index);
      console.log('====================================');
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

let humanModalVisible = ref(false),
  humanModalType = ref(0), // 1 组织负责人 2 分管领导,
  currIndex = 0;
// 显示人员弹框
const showHumanModal = (type: number, index: number) => {
  if (type === 1) {
    rowSelection.type = 'radio';
  } else {
    rowSelection.type = 'checkbox';
    rowSelection.showCheckedAll = true;
  }
  humanModalType.value = type;
  currIndex = index;
  humanModalVisible.value = true;
};

const humanRosterEmit = async (record: any) => {
  try {
    console.log('========record============================');
    console.log(record);
    console.log('====================================');
    const temp = formData.organizationLists[currIndex].organizationValue;
    if (humanModalType.value === 1) {
      temp.responserName = record['C62B8DC31189847E0972B5D8F721404B1'];
      temp.responsibleId = record.id;
      if (record?.['C7341027925C943708F3AEF98703ECC47']) {
        const res = await GetPositionDefault({
          id: +record?.['C7341027925C943708F3AEF98703ECC47']
          // id: +11
        });
        temp.positionName = res.name;
      }
    } else {
      temp.leaderName = [];
      temp.leaderId = [];
      record.forEach((el: any) => {
        temp.leaderName.push({
          name: el['C62B8DC31189847E0972B5D8F721404B1'],
          id: el.id
        });
        temp.leaderId.push(el.id);
      });
      // temp.leaderName = temp.leaderName.join(',');
      // temp.leaderName.join(',');
      // temp.leaderId.join(',');
      console.log('========temp============================');
      console.log(temp);
      console.log(formData);
      console.log('====================================');
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 新增一项
const add = (index: number) => {
  formData.organizationLists.splice(index + 1, 0, cloneDeep(tempItem));
  templateList.value.push([]);
  console.log('====================================');
  console.log(templateList.value);
  console.log('====================================');
};

const del = (index: number) => {
  formData.organizationLists.splice(index, 1);
};

let refForm = ref(); // 储存表单的ref
// 保存
const handleOk = async (isContinue = false) => {
  let totalHeadCount = 0;
  formData.organizationLists.forEach((item: any) => {
    item.organizationValue.superiorId = formData.superiorId
      ? formData.superiorId
      : 0;
    item.superiorId = item.organizationValue.superiorId;
    item.name = item.organizationValue.name;
    item.organizationUniqueCode = item.organizationValue.organizationUniqueCode;
    item.ownerId = +item.organizationValue.ownerId;
    item.node = item.organizationValue.node;
    item.enable = +item.organizationValue.enable;
    item.positionName = item.organizationValue.positionName;
    item.responsibleId = +item.organizationValue.responsibleId;
    item.headcount = +item.organizationValue.headcount;
    item.responserName = item.organizationValue.responserName;
    item.organizationValue.leaderId =
      item.organizationValue.leaderId?.length > 0
        ? item.organizationValue.leaderId?.join(',')
        : '';
    item.organizationValue.leaderName =
      item.organizationValue.leaderName?.length > 0
        ? item.organizationValue.leaderName
            ?.map((el: any) => el?.name)
            ?.join(',')
        : '';
    item.leaderId = item.organizationValue.leaderId;
    item.leaderName = item.organizationValue.leaderName;

    totalHeadCount += +item.headcount;
  });
  if (await refForm.value.validate()) {
    emit('update:visible', true);
    return;
  } else if (
    currSuperiorData.controlType !== 1 &&
    totalHeadCount > maxDisposableHeadCount.value
  ) {
    Message.error('编制人数不能超过最大可支配的编制人数！');
    emit('update:visible', true);
    return;
  }
  console.log('=========formData===========================');
  console.log(formData);
  console.log('====================================');
  emit('organizationAddEmit', cloneDeep(formData));

  formData.superiorId = undefined;
  formData.organizationLists = [cloneDeep(tempItem)];
  if (isContinue) {
    emit('update:visible', true);
  } else emit('update:visible', false);
};

// 取消
const handleCancel = () => {
  emit('update:visible', false);
  formData.superiorId = undefined;
  formData.organizationLists = [cloneDeep(tempItem)];
};
</script>

<style scoped lang="less">
:deep(.arco-tree-node-indent) {
  width: 0px;
  height: 0px;
}
.icon {
  cursor: pointer;
  font-size: 20px;
}

.star::before {
  content: '*';
  color: red;
}
:deep(.arco-table-th),
:deep(.arco-table-td) {
  height: 60px;
}

.operation {
  position: relative;
  bottom: 10px;
}
</style>
